package com.jxwifi.cloud.quickclean.mycenter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.AssOrderAdapter;
import com.jxwifi.cloud.quickclean.adapter.FeedbackAdapter;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.assemble.ADetailsActivity;
import com.jxwifi.cloud.quickclean.assemble.AssembleOrderPresenter;
import com.jxwifi.cloud.quickclean.bean.CollageRecordsBean;
import com.jxwifi.cloud.quickclean.bean.FeedBackBean;
import com.jxwifi.cloud.quickclean.bean.FeedbackRecordsBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.view.SuperSwipeRefreshLayout;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jxwifi.cloud.quickclean.R.id.imageView;

/**
 * Created by Administrator on 2020/7/20.
 */

public class FeedBackActivity extends ClientBasicActivity {

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.rv_feedback_list)
    RecyclerView rv_feedback_list;
    @Bind(R.id.srl_feedback_list)
    SuperSwipeRefreshLayout srl_feedback_list;
    @Bind(R.id.et_content)
    EditText et_content;
    @Bind(R.id.btn_send)
    Button btn_send;

    private int mPageIndex = 1;//页数
    private int mLimit=10000;
    private AuzImpl mAuz;
    private FeedbackRecordsBean mBeanList;
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    private int mCurrentCounter;//获取的数据个数
    private FeedbackAdapter mAdapter;
    public Context mBaseContext;
    private boolean isErr = true;
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    private boolean unreadMessages = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        mBaseContext = this;
        ButterKnife.bind(this);
        openEventBus();
        mAuz = new AuzImpl();
        unreadMessages = getIntent().getBooleanExtra("unreadMessages",false);

        //mPresenter=new AssembleOrderPresenter(mBaseContext,this);
    }

    @OnClick({R.id.rel_img_back_pressed, R.id.btn_send})
    void clickCK(View v){
        switch (v.getId()){
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            case R.id.btn_send:
                /*new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                    }
                }, 1000);*/
                sendContent();

                break;
        }
    }

    public void initData(){  //CollageRecordsBean

        Params params = new Params();
        params.add("limit", mLimit);
        params.add("page", mPageIndex);
        params.add("unreadMessages", unreadMessages);
        Log.i(TAG,"unreadMessages = "+unreadMessages);
        mAuz.auzget(UrlPool.GET_FEEDBACK_LIST, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {

                mBeanList= JSON.parseObject(data, FeedbackRecordsBean.class);
                Log.i(TAG,"mBeanList.getSize = "+mBeanList.getSize()+" 聊天记录size = "+mBeanList.getRecords().size());
                mTotalNum = mBeanList.getTotal();
                Log.i(TAG,"mTotalNum = "+mTotalNum);
                //Log.i(TAG,"mBeanList.getSize = "+mBeanList.getSize());
                if (mBeanList.getSize()>0){
                    //mView.getOrderList().setVisibility(View.VISIBLE);
                   // mView.getListNull().setVisibility(View.GONE);
                    /*for (int i = 0; i < mBeanList.getRecords().size(); i++) {
                        Log.i(TAG,"回复类型 = "+mBeanList.getRecords().get(i).getReplyType()+" 回复内容 = "+mBeanList.getRecords().get(i).getContent());
                    }*/
                    if (mPageIndex == 1){
                        FeedBackBean feedBackBean = new FeedBackBean();
                        feedBackBean.setTitle("Android Client");
                        feedBackBean.setReplyType("SYS");
                        feedBackBean.setContent("尊敬的顾客，您在使用过程中，如果有任何用得不是很舒服的地方，可随时反馈给我们，我们会用心倾听您的心声，全力完善这个软件，不断给您带来更优质的用户体验~");
                        mBeanList.getRecords().add(0,feedBackBean);

                        setData(true, mBeanList.getRecords());
                    }else{
                        setData(false, mBeanList.getRecords());
                    }
                    //mAdapter.setNewData(mBeanList.getRecords());
                }else{
                    //mView.getOrderList().setVisibility(View.GONE);
                    //mView.getListNull().setVisibility(View.VISIBLE);
                    //mView.getSwip().setEnabled(false);
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        });
    }

    private void sendContent(){
        unreadMessages = false;
        Params params=new Params();
        //Log.i(TAG,"sendContent() ==> 发送内容 = "+et_content.getText().toString());
        String content = et_content.getText().toString();
        params.add("title","Android Client");
        params.add("unreadMessages",unreadMessages);
        //params.add("content",et_content.getText().toString());
        try {
            params.add("content", URLEncoder.encode(content,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mAuz.auzpost(UrlPool.POST_POURFORTH, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if(code == 0){
                    Toast toast = Toast.makeText(mBaseContext, "发送成功", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 1000);
                    et_content.setText("");
                    mPageIndex = 1;
                    unreadMessages = false;
                    initData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                //Log.i(TAG,"sendContent ==> errorCode = "+errorCode+" msg = "+msg);
                Toast toast = Toast.makeText(mBaseContext, "发送失败", Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 1000);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,"onResume ==> ");
        mPageIndex = 1;
        initView();
    }

    public void initView() {
        rv_feedback_list.setLayoutManager(new LinearLayoutManager(this));
        rv_feedback_list.setAdapter(mAdapter = new FeedbackAdapter(R.layout.activity_feedback_item));
        initData();

        //上拉加载更多操作
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                rv_feedback_list.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentCounter >= mTotalNum) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                        } else {
                            if (isErr) {
                                initData();
                                //成功获取更多数据
                                mCurrentCounter = mAdapter.getData().size();
                                mAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
                                isErr = true;
                                Toast.makeText(mBaseContext, "获取更多数据失败", Toast.LENGTH_LONG).show();
                                mAdapter.loadMoreFail();
                            }
                        }
                    }
                }, 1500);

            }
        },rv_feedback_list);


        srl_feedback_list.setHeaderView(createHeaderView());
        srl_feedback_list.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        srl_feedback_list.setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        mPageIndex = 1;
                        initData();
                    }
                }, 1000);
            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
    }

    public void setData(boolean isRefresh, List data) {
        Log.i(TAG,"mPageIndex = "+mPageIndex);
        mPageIndex++;
        final int size = data == null ? 0 : data.size();

        if (isRefresh) {
            srl_feedback_list.setEnabled(true);
            mAdapter.setNewData(data);

        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        mCurrentCounter = mAdapter.getData().size();
        if (size < mLimit) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
        //Log.i(TAG,"setData定位 size = "+ (mBeanList.getRecords().size()-1)+"");
        rv_feedback_list.scrollToPosition(mBeanList.getRecords().size()-1);
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(srl_feedback_list.getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }


    private void setEmojiToTextView() {
        int unicodeJoy = 0x1F602;
        String emojiString = getEmojiStringByUnicode(unicodeJoy);
        //myTextView.setText(emojiString);
    }

    private String getEmojiStringByUnicode(int unicode) {
        return new String(Character.toChars(unicode));
    }


}

